import 'package:flame/components.dart';
import 'package:flutter/animation.dart';
import '../../state/SeedSelectionState.dart';
import '../../../../config/GameConfig.dart';
import '../../../../component/SpriteEntity.dart';
import '../CameraController.dart';
import '../idleZombie/IdleZombie.dart';
import '../idleZombie/IdleZombieManager.dart';
import '../menuButton/MenuButton.dart';
import '../seedChooserBank/SeedChooserBank.dart';

class BasicStage extends SpriteEntity with GameConfig {
  BasicStage(super.spriteImg, {required this.onCompleted});

  late SeedChooserBank seedChooserBank; // 种子商店
  late IdleZombieManager idleZombieManager; // 静止的僵尸
  late CameraController cameraController; // 镜头
  VoidCallback onCompleted; // 选择完成回调函数
  late MenuButton menuButton;

  @override
  Future<void> onLoad() async {
    await super.onLoad();
    final radio = sprite!.image.width / sprite!.image.height;
    final worldHeight = GameConfig.gameScreenHeight;
    final worldWidth = radio * worldHeight;
    size = Vector2(worldWidth, worldHeight);
    priority = backgroundPriority;

    // 初始化镜头
    final cameraWidth = worldHeight * basicStageCameraWidthFactor; // 右边刚好出草坪
    game.camera = CameraComponent.withFixedResolution(
      width: cameraWidth,
      height: worldHeight,
    );
    game.camera.viewfinder.anchor = Anchor.topLeft;
    cameraController = CameraController(game.camera);
    // 移动视角到右侧
    final seedState = SeedSelectionState();
    seedChooserBank = SeedChooserBank(
      onCompleted: moveCameraBack,
      state: seedState,
    );
    cameraController.moveTo(
      Vector2(worldWidth - cameraWidth, 0),
      onComplete: () => add(seedChooserBank),
      duration: 1,
    );
    // 添加静止的僵尸
    idleZombieManager = IdleZombieManager();
    add(idleZombieManager);
    idleZombieManager.spawnIdleZombies();
    // 菜单
    _generateMenu();
  }

  // 移除静止的僵尸
  void removeIdleZombie() {
    children.whereType<IdleZombie>().forEach((e) => e.removeFromParent());
  }

  // 移动视角回到战斗视角
  void moveCameraBack() {
    seedChooserBank.readyForFight();
    menuButton.readyForFight();
    cameraController.moveTo(
      Vector2.zero(),
      onComplete: () {
        removeIdleZombie();
        onCompleted.call();
      },
      duration: 2,
    );
  }

  // 生成菜单
  void _generateMenu() {
    menuButton = MenuButton();
    add(menuButton);
  }
}
